﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Agents.Admin
{
    //page allows administrator to create a new discount number:
    //for example- discount number 4 gives 15% discount.
    public partial class NewPriceList : System.Web.UI.Page
    {
        #region Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        //function is activated when the ok button is clicked.
        protected void okBtn_Click(object sender, EventArgs e)
        {
            // New Price List
            if (panelNewPriceList.Visible)
            {
                CreateNewPriceList();
            }
            // Change Prices
            else if (panelChangePrices.Visible)
            {
                ChangePrices();
            }
        }

        //function for redirecting the administrater back to his home page without adding a new discount number
        protected void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }

        /// <summary>
        /// Occurs when the action changes and shows the right panel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void radAction_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelNewPriceList.Visible = (radAction.SelectedValue == "NewPriceList");
            panelChangePrices.Visible = (radAction.SelectedValue == "ChangePrices");
        }

        /// <summary>
        /// Occurs when the affected products change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void radProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            Queries queries = new Queries();

            switch (radProducts.SelectedValue)
            {
                // Affect all products - hide the products dropdown
                case ("All"):
                {
                    cmbProducts.Visible = false;
                    break;
                }
                // Affect by category - show the products dropdown to select a category
                case ("ByCategory"):
                {
                    cmbProducts.Visible = true;
                    cmbProducts.DataSource = queries.GetAllCategories();
                    cmbProducts.DataTextField = "Name";
                    cmbProducts.DataValueField = "Id";
                    cmbProducts.DataBind();
                    break;
                }
                // Affect one product - show the products dropdown to select a product
                case ("One"):
                {
                    cmbProducts.Visible = true;
                    cmbProducts.DataSource = queries.GetAllProducts();
                    cmbProducts.DataTextField = "Name";
                    cmbProducts.DataValueField = "Id";
                    cmbProducts.DataBind();
                    break;
                }
            }
        }

        /// <summary>
        /// Redirect back to the admin menu after a few seconds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void redirectionTimer_Tick(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Creates a new price list
        /// </summary>
        private void CreateNewPriceList()
        {
            Queries queries = new Queries();

            //making sure the discount number doesnt already exist in the database
            if (queries.ExistsPriceList(numberTxtbox.Text) == false)
            {
                // Disable the buttons
                backBtn.Enabled = false;
                okBtn.Enabled = false;

                //add new discount number to the database and redirecting to homepage.
                queries.AddPriceList(numberTxtbox.Text, Double.Parse(discountPrecentTxtbox.Text));

                // Announce success and wait for 2 seconds before redirecting
                lblMessage.Text = "המחירון נוסף בהצלחה";
                redirectionTimer.Enabled = true;
            }
            //alresdy exists
            else
            {
                lblMessage.Text = "קיים מחירון עם המספר שהוזן";
            }
        }

        /// <summary>
        /// Change the prices by the details
        /// </summary>
        private void ChangePrices()
        {
            // Disable the buttons
            backBtn.Enabled = false;
            okBtn.Enabled = false;

            Queries queries = new Queries();
            List<Product> affectedProducts = new List<Product>();

            // Get the affected products
            switch (radProducts.SelectedValue)
            {
                // Change all products
                case ("All"):
                {
                    affectedProducts = queries.GetAllProducts().ToList();
                    break;
                }
                // Change by category
                case ("ByCategory"):
                {
                    int categoryId = Int32.Parse(cmbProducts.SelectedValue);
                    affectedProducts = queries.GetAllProductsOfCategory(
                                                        categoryId).ToList();
                    break;
                }
                // Change one product
                case ("One"):
                {
                    int productId = Int32.Parse(cmbProducts.SelectedValue);
                    affectedProducts = new List<Product>() 
                                        { queries.GetProduct(productId) };
                    break;
                }
            }

            // Whether to reduce or raise prices
            int factor = (radReduceRaise.SelectedValue == "Raise") ? 1 : -1;

            // Get the value
            double value = Double.Parse(txtChangeValue.Text);

            // Go over the products and change their prices
            foreach (Product product in affectedProducts)
            {
                double newPrice = product.Price;

                // Absolute
                if (radUnits.SelectedValue == "Absolute")
                {
                    newPrice = newPrice + factor * value;
                }

                // Precentage
                else if (radUnits.SelectedValue == "Precentage")
                {
                    newPrice = newPrice * (1 + factor * (value / 100));
                }

                queries.EditProduct(product.Id,
                            product.Name,
                            newPrice,
                            product.CategoryId,
                            product.Threshold,
                            product.NotifyBelowThreshold,
                            product.MaxDaysFromLastOrder,
                            product.NotifyUnordered);
            }

            // Announce success and wait for 2 seconds before redirecting
            lblMessage.Text = "המחירים התעדכנו בהצלחה";
            redirectionTimer.Enabled = true;
        }

        #endregion
    }
}